package main

import (
	"log"
	"math"
	"math/rand"
	"sort"
	"time"
	"xiehui-service/app/models"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/services/types"

	"gorm.io/gorm"
)

var (
	ConcretePumpInterval    = 15 * 60 * time.Second // 泵送时间间隔15分钟
	ConcreteNotPumpInterval = 30 * 60 * time.Second // 非泵送时间间隔30分钟
	VehicleAvgCapacity      = 10                    // 车平均方量
	PlanConflictAddInterval = 60 * time.Second      //随机时间
)

type Plugin struct {
}

func (p *Plugin) GenerateSDPlan(orderTask []erp_models.OrderTask) (sdPlan types.PlanSlice, err error) {
	for _, t := range orderTask {
		var interval time.Duration
		if t.BuildMethod == "2" {
			if t.AutoRatio == 50 {
				interval = ConcreteNotPumpInterval * 2
			} else if t.AutoRatio == 200 {
				interval = ConcreteNotPumpInterval / 2
			} else {
				interval = ConcreteNotPumpInterval
			}
			log.Println("非泵任务", t.ID.ID, "间隔", interval)
		} else {
			if t.AutoRatio == 50 {
				interval = ConcretePumpInterval * 2
			} else if t.AutoRatio == 200 {
				interval = ConcretePumpInterval / 2
			} else {
				interval = ConcretePumpInterval
			}
			log.Println("泵送任务", t.ID.ID, "系数", t.AutoRatio/100, "间隔", interval)
		}

		// 剩余方量计算，暂停方量为0 使用计划方量，否则使用暂停方量
		var unDeliveryQuantity float64
		if t.PauseQuantity == 0 {
			log.Println("暂停方量为0, 使用计划方量:", t.PlanQuantity)
			unDeliveryQuantity = t.PlanQuantity - t.DeliveryQuantity
		} else {
			log.Println("暂停方量:", t.PauseQuantity)
			unDeliveryQuantity = t.PauseQuantity - t.DeliveryQuantity
		}

		if unDeliveryQuantity <= 0 {
			log.Println("任务剩余方量小于0, 无法自动排车")
			continue
		}
		//Ceil向上取整 Floor向下取整
		estimatedDeliveryNumber := int(math.Floor(unDeliveryQuantity / float64(VehicleAvgCapacity)))
		log.Println("任务", t.ID.ID, "剩余方量", unDeliveryQuantity, "预估剩余满载车数", estimatedDeliveryNumber)
		log.Println("上次发车距现在: ", time.Since(*t.LastDispatchTime))
		var sdPlanStartAt time.Time
		if time.Since(*t.LastDispatchTime) < interval {
			sdPlanStartAt = t.LastDispatchTime.Add(interval)
		} else {
			sdPlanStartAt = time.Now()
		}
		// 解决：距离上次排车时间过长，导致立刻排车的问题，统一增加30秒
		sdPlanStartAt = sdPlanStartAt.Add(time.Second * 30)
		log.Println("计划开始时间: ", sdPlanStartAt)

		for i := 0; i < estimatedDeliveryNumber; i++ {
			planTime := sdPlanStartAt.Add(interval*time.Duration(i) + time.Duration(rand.Float64()*10)*time.Second) //添加一个随机事件
			sdPlan = append(sdPlan, erp_models.OrderAutoDispatchPlan{StartTime: planTime, TaskId: int64(t.ID.ID), Interval: int8(interval.Minutes()), Current: 1, State: 0, SoftDeletes: models.SoftDeletes{
				DeletedAt: gorm.DeletedAt{Valid: false},
			}})
		}

	}

	sort.Sort(sdPlan)

	return
}

// export NewPlugin
func NewPlugin() interface{} {
	return &Plugin{}
}
